import axios from 'axios'
import qs from 'qs'// 引入qs模块，用来序列化post类型的数据
import { baseURL } from "./assets/js/config.js"
// 导入vuex，拿到状态对象
import store from './store';

const Axios = axios.create({
  baseURL: baseURL,
  // withCredentials: true,//携带证书
  timeout: 5000
});

// post请求头设置
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

// 请求拦截器
Axios.interceptors.request.use(
  config => {
    console.log("进入请求拦截器...")
    //this.axios.post(
    //"user/login",url
    //{uname:dingding , upwd:123456} 
    //)
    if (config.method == "post") {//post方法，将data序列化
      config.data = qs.stringify(config.data);
    }

    if (sessionStorage.getItem("token")) {//如果sessionstorage中有token 
      config.headers.token = sessionStorage.getItem("token");
    }
    console.log("出")
    return config;
  },
  error => {
    console.log("===发送请求拦截器报错===")
    console.log(error);
    console.log("===end===");
    return Promise.reject(error);
  }
)
// 响应拦截器
Axios.interceptors.response.use(
  res => {
    console.log("触发响应拦截器...")
    console.log(res)
    if (res.data.code === 403) {    //token拦截器未通过，响应403，清除token        
      localStorage.removeItem("token");
      sessionStorage.removeItem("token");
      store.commit("setIslogin", false);
      store.commit("setUname", "");
    } else if (res.data.code == 201) {   //后端没有查询到用户，请先登录
      store.commit("setIslogin", false);
      store.commit("setUname", "");
    } else if (res.data.token) {//查询到用户
      store.commit("setId", res.data.lid);
      store.commit("setWallet", res.data.wallet);
      store.commit("setUname", res.data.username);
      store.commit("setIslogin", true);
      if (res.remember === "true") {//存放到localstorage
        localStorage.setItem("token", res.data.token);
      } else {//存放到sessionstorage
        sessionStorage.setItem("token", res.data.token);
      }
      console.log("出")
    }
    console.log('出')
    return res;
  },
  // 服务器状态码403
  // 错误状态码    
  // 路由重定向到登录
  err => {
    if (err.response.code == 403) {
      router.replace({
        path: '/login',
        query: {
          redirect: router.currentRoute.fullPath
        }
      });
      return Promise.reject(err.response);
    }
  }
);

// 导出
export default Axios;

